﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Windows;

namespace NUnit.Phone.Gui
{
    /// <summary>
    /// Contains the helper methods for the View layer.
    /// </summary>
    public static class ViewHelper
    {
        /// <summary>
        /// Retrieves the page associated with a specific element.
        /// </summary>
        /// <param name="element">The reference element.</param>
        /// <returns>
        /// The page associated with <paramref name="element"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="element"/> parameter is <c>null</c>.
        /// </exception>
        public static T RetrieveParent<T>(this FrameworkElement element)
            where T : FrameworkElement
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            T result;

            // Test the element itself
            result = element as T;
            if (result != null)
            {
                return result;
            }

            // Test the parent element
            if (element.Parent == null || !(element.Parent is FrameworkElement))
            {
                return null;
            }
            else
            {
                return RetrieveParent<T>(element.Parent as FrameworkElement);
            }
        }
    }
}
